unit uAppLog;

interface

uses
  SysUtils, SyncObjs, Windows, uDZSysUtils, uDZTrace, uDZProcess,
  uDZLogWritter, uAppCmdLineParams;

procedure WriteLog(sev: TDzTraceSeverity; const s: string);
procedure FmtWriteLog(sev: TDzTraceSeverity; const fmt: string;
  const args: array of const);
procedure Performance_WriteLog(const s: string);
procedure Performance_FmtWriteLog(const fmt: string; const args: array of const);
procedure LogException(const func: string; E: Exception);

implementation

var
  lock: TSynchroObject;
  trace: IDzTrace;
  plock: TSynchroObject;
  ptrace: IDzTrace;

procedure WriteLog(sev: TDzTraceSeverity; const s: string);
begin
  lock.Acquire;
  try
    trace.Write(sev, s);
  finally
    lock.Release;
  end;
end;

procedure FmtWriteLog(sev: TDzTraceSeverity; const fmt: string;
  const args: array of const);
begin
  lock.Acquire;
  try
    trace.FormatWrite(sev, fmt, args);
  finally
    lock.Release;
  end;
end;

procedure Performance_WriteLog(const s: string);
begin
  plock.Acquire;
  try
    ptrace.Write(tsWarning, s);
  finally
    plock.Release;
  end;
end;

procedure Performance_FmtWriteLog(const fmt: string; const args: array of const);
begin
  plock.Acquire;
  try
    ptrace.FormatWrite(tsWarning, fmt, args);
  finally
    plock.Release;
  end;
end;

procedure LogException(const func: string; E: Exception);
begin
  WriteLog(tsError, Format('%s[%s]: %s'#10, [func, E.ClassName, E.Message]));
end;

initialization
  lock := TCriticalSection.Create;
  plock := TCriticalSection.Create;
  if cmdLineParams.LogType = altConsole then
  begin
    Windows.AllocConsole;
    trace := TConsoleTrace.Create;
    ptrace := TConsoleTrace.Create;
  end
  else begin
    trace := TDzMultiFileLogWritter.Create(
      ExtractFilePath(ParamStr(0)) + 'log');
    ptrace := TDzFileTrace.Create(ExtractFilePath(ParamStr(0)) +
      'PerformanceLog\' + FormatDateTime('yyyy-mm-dd hh_nn_ss', Now) + '.log');
  end;
  if CmdLineParams.DebugMode then trace.Severity := TRACE_SEVERITIES_ALL
  else trace.Severity := [tsError, tsWarning];
  trace.Options := trace.Options - [toSeverityTag];
  trace.Attributes['Encoding'] := teAnsi;
  trace.Attributes['LogSeparate'] := dtpHour;
  trace.DateTimeFormat := 'hh:nn:ss';
  if CmdLineParams.DebugMode then ptrace.Severity := TRACE_SEVERITIES_ALL
  else ptrace.Severity := [tsError, tsWarning];
  ptrace.Options := ptrace.Options - [toSeverityTag];
  ptrace.Attributes['Encoding'] := teAnsi;
  ptrace.DateTimeFormat := 'yyyy-mm-dd hh:nn:ss';


finalization
  lock.Free;
  plock.Free;

end.
